<template>
  <div class="profile-container">
    <a-card title="个人资料" :bordered="false">
      <div class="avatar-uploader">
        <div class="avatar-wrapper">
          <img v-if="userInfo.avatar" :src="getStaticUrl(userInfo.avatar)" alt="头像" class="avatar-image" />
          <div v-else class="avatar-placeholder">{{ getInitials(userInfo.nickname || userInfo.username) }}</div>
        </div>
        <a-upload
          name="file"
          :show-upload-list="false"
          :before-upload="beforeUpload"
          :customRequest="handleUpload"
          accept="image/*"
        >
          <a-button type="primary">更换头像</a-button>
        </a-upload>
      </div>
      
      <a-form
        :model="formState"
        layout="vertical"
        @finish="handleSubmit"
        class="profile-form"
      >
        <a-form-item
          label="用户名"
          name="username"
        >
          <a-input v-model:value="formState.username" disabled />
        </a-form-item>
        
        <a-form-item
          label="昵称"
          name="nickname"
          :rules="[{ required: true, message: '请输入昵称' }]"
        >
          <a-input v-model:value="formState.nickname" />
        </a-form-item>
        
        <a-form-item
          label="邮箱"
          name="email"
          :rules="[
            { required: true, message: '请输入邮箱' },
            { type: 'email', message: '请输入有效的邮箱地址' }
          ]"
        >
          <a-input v-model:value="formState.email" />
        </a-form-item>
        
        <a-form-item
          label="个人简介"
          name="bio"
        >
          <a-textarea v-model:value="formState.bio" :rows="4" />
        </a-form-item>
        
        <a-form-item>
          <a-button type="primary" html-type="submit" :loading="submitting">保存修改</a-button>
        </a-form-item>
      </a-form>
    </a-card>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted } from 'vue';
import { message } from 'ant-design-vue';
import { useUserStore } from '@/stores/user';
import { updateUserInfo } from '@/api/auth';
import { uploadAvatar } from '@/api/upload';
import { getStaticUrl } from '@/utils/url';

const userStore = useUserStore();
const userInfo = ref({
  id: '',
  username: '',
  nickname: '',
  email: '',
  avatar: '',
  bio: ''
});
const submitting = ref(false);

const formState = reactive({
  username: '',
  nickname: '',
  email: '',
  bio: ''
});

onMounted(async () => {
  await fetchUserInfo();
});

const fetchUserInfo = async () => {
  try {
    // 如果没有用户信息，则获取
    if (!userStore.userInfo) {
      await userStore.getUserInfo();
    }
    
    // 从store中获取用户信息
    userInfo.value = userStore.userInfo || {};
    
    // 初始化表单数据
    formState.username = userInfo.value.username || '';
    formState.nickname = userInfo.value.nickname || '';
    formState.email = userInfo.value.email || '';
    formState.bio = userInfo.value.bio || '';
  } catch (error) {
    console.error('获取用户信息失败', error);
    message.error('获取用户信息失败');
  }
};

const handleSubmit = async () => {
  submitting.value = true;
  try {
    await updateUserInfo({
      nickname: formState.nickname,
      email: formState.email,
      bio: formState.bio
    });
    
    message.success('个人资料更新成功');
    
    // 更新全局用户信息
    await userStore.getUserInfo();
    userInfo.value = userStore.userInfo;
  } catch (error) {
    console.error('更新个人资料失败', error);
    message.error('更新失败');
  } finally {
    submitting.value = false;
  }
};

// 上传头像前的验证
const beforeUpload = (file) => {
  const isImage = file.type.startsWith('image/');
  if (!isImage) {
    message.error('只能上传图片文件!');
  }
  
  const isLt2M = file.size / 1024 / 1024 < 2;
  if (!isLt2M) {
    message.error('图片必须小于2MB!');
  }
  
  return isImage && isLt2M;
};

// 处理头像上传
const handleUpload = async ({ file }) => {
  const formData = new FormData();
  formData.append('file', file);
  
  try {
    message.loading({ content: '上传中...', key: 'avatar' });
    const result = await uploadAvatar(formData);
    
    if (result && result.url) {
      message.success({ content: '头像上传成功', key: 'avatar' });
      
      // 更新全局用户信息
      await userStore.updateAvatar(result.url);
      userInfo.value.avatar = result.url;
    }
  } catch (error) {
    console.error('上传头像失败', error);
    message.error({ content: '上传失败', key: 'avatar' });
  }
};

// 获取名字缩写用于头像占位符
const getInitials = (name) => {
  if (!name) return '用户';
  return name.charAt(0).toUpperCase();
};
</script>

<style scoped>
.profile-container {
  max-width: 800px;
  margin: 0 auto;
  padding: 20px;
}

.avatar-uploader {
  text-align: center;
  margin-bottom: 30px;
}

.avatar-wrapper {
  margin-bottom: 15px;
  display: inline-block;
}

.avatar-image {
  width: 100px;
  height: 100px;
  border-radius: 50%;
  object-fit: cover;
  border: 2px solid #f0f0f0;
}

.avatar-placeholder {
  width: 100px;
  height: 100px;
  border-radius: 50%;
  background-color: #1890ff;
  color: #fff;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 36px;
  font-weight: bold;
}

.profile-form {
  max-width: 500px;
  margin: 0 auto;
}
</style> 